// https://taro-ext.jd.com/plugin/view/5d394d3a9b6a1d4027780173
import React, { useEffect, useState } from "react";
import Taro, {
  useReachBottom,
  usePullDownRefresh,
  useRouter,
  useDidShow,
} from "@tarojs/taro";
import GoodsItem from "@/components/GoodsItem";
import onPay from "@/common/utils/pay";
import createContract from "@/common/utils/createContract";
import { View, Image, Text } from "@tarojs/components";

import ListStatusInfo from "@/components/ListStatusInfo";

import * as api from "./api";
import "./index.scss";

const Index: React.FC<{}> = () => {
  const [data, setData] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [activeKey, setActiveKey] = useState("all");
  const router = useRouter();
  const [tabMap, setTabMap] = useState<any>({
    all: {
      text: "全部订单",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    order_launched: {
      text: "待支付",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    payment_finished: {
      text: "待发货",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    delivery_finished: {
      text: "待收货",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    order_finished: {
      text: "已完成",
      total: null,
      current: null,
      data: [],
      isShow: true,
      isLoaded: false,
    },
    order_closed: {
      text: "已取消",
      total: null,
      current: null,
      data: [],
      isShow: false,
      isLoaded: false,
    },
  });

  const getList = async (current_page = 1) => {
    try {
      setLoading(true);
      Taro.showNavigationBarLoading();
      const { result, status } = await api.customer_order_search({
        search_info: JSON.stringify({
          status: activeKey === "all" ? undefined : activeKey,
        }),
        current_page: current_page,
      });
      if (status === "ok") {
        const newTabMap = { ...tabMap };
        newTabMap[activeKey].current = current_page;
        newTabMap[activeKey].isLoaded = true;
        newTabMap[activeKey].data =
          current_page === 1
            ? [].concat(result.data_list)
            : newTabMap[activeKey].data.concat(result.data_list);
        newTabMap[activeKey].total = result.total;
        setTabMap(newTabMap);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideNavigationBarLoading();
      Taro.stopPullDownRefresh();
      setLoading(false);
    }
  };

  useReachBottom(() => {
    if (tabMap[activeKey].data.length < tabMap[activeKey].total) {
      getList(tabMap[activeKey].current + 1);
    }
  });

  usePullDownRefresh(() => {
    getList(1);
  });

  useDidShow(() => {
    if (!tabMap[activeKey].isLoaded) {
      getList(1);
    }
  });

  useEffect(() => {
    if (!tabMap[activeKey].isLoaded) {
      getList(1);
    }
  }, [activeKey]);

  const orderCancel = async (order_id) => {
    try {
      Taro.showLoading();
      const { result, status } = await api.customer_order_cancel({
        order_id,
      });
      if (status === "ok") {
        getList(1);
        const newTabMap = { ...tabMap };
        newTabMap["all"].isLoaded = false;
        setTabMap(newTabMap);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideLoading();
    }
  };

  return (
    <View className="order-list-page">
      <View className="tabs">
        {Object.entries(tabMap).map((item) => {
          if (item[1].isShow) {
            return (
              <View
                key={item[0]}
                className={activeKey === item[0] ? "tab tab__active" : "tab"}
                onClick={() => {
                  setActiveKey(item[0]);
                }}
              >
                {item[1].text}
                <View className="line"></View>
              </View>
            );
          }
        })}
      </View>

      {/* {JSON.stringify(item.order_item_list)} */}

      {tabMap[activeKey].data.map((item) => {
        return item.order_item_list.map((it) => {
          return (
            <View key={it.id + item} className="order-item-card">
              <GoodsItem
                className="goods-wrapper"
                {...it}
                thumbnail={it.show_image}
                status={item.status}
                category={it.category}
                onClick={() => {
                  Taro.navigateTo({
                    url: "/pages/orderDetail/index?order_id=" + item.id,
                  });
                }}
                count={it.quantity}
              />
              <View className="footer-info">
                <View className="money">
                  {/* <Text>总价：{(item.sale_price / 100).toFixed(2)}，</Text>
                  {item.discount ? (
                    <Text>优惠：{(item.discount / 100).toFixed(2)}，</Text>
                  ) : null} */}
                  {item.arrears ? (
                    <Text>欠缴:{(item.arrears / 100).toFixed(2)}，</Text>
                  ) : null}

                  <Text>
                    {item.status === "order_launched" ||
                    item.status === "order_closed"
                      ? `需付款:￥${(item.deposit / 100).toFixed(2)}`
                      : `实付款:${(item.actual_amount / 100).toFixed(2)}`}
                  </Text>
                </View>
              </View>
              {item.status === "order_finished" &&
                item.despatch_type === "eduction_contract" && (
                  <View className="btn-con">
                    <View
                      className="btn"
                      onClick={() => {
                        createContract(item.order_item_list[0].contract_id, (contract_info) => {
                          Taro.navigateTo({
                            url: `/pages/contratPreview/index?params=${JSON.stringify(
                              contract_info
                            )}`,
                          });
                        });
                      }}
                    >
                      查看合同
                    </View>
                  </View>
                )}

              {item.status === "order_launched" && (
                <View className="btn-con">
                  <View
                    className="btn btn__gray"
                    onClick={() =>
                      Taro.showModal({
                        title: "提示",
                        content: "您确定取消该订单吗？",
                        success: function (res) {
                          if (res.confirm) {
                            orderCancel(item.id);
                          }
                        },
                      })
                    }
                  >
                    取消
                  </View>
                  <View
                    className="btn"
                    onClick={() => {
                      onPay(item.id, () => {
                        getList(1);
                        const newTabMap = { ...tabMap };
                        newTabMap["all"].isLoaded = false;
                        setTabMap(newTabMap);
                      });
                    }}
                  >
                    支付
                  </View>
                </View>
              )}

              {item.status === "delivery_finished" &&
                item.despatch_type === "eduction_contract" && (
                  <View className="btn-con">
                    <View
                      className="btn"
                      onClick={() => {
                        createContract(item.order_item_list[0].contract_id, (contract_info) => {
                          const params = {
                            invoice_info: item.invoice_info,
                            contract_info,
                          };
                          Taro.navigateTo({
                            url: `/pages/signContract/index?params=${JSON.stringify(
                              params
                            )}`,
                          });
                        });
                      }}
                    >
                      签署合同
                    </View>
                  </View>
                )}
            </View>
          );
        });
      })}

      <ListStatusInfo
        total={tabMap[activeKey].total}
        dataLength={tabMap[activeKey].data.length}
        loading={loading}
      />
    </View>
  );
};

export default Index;
